/*
 * @Author: yangzonglong
 * @Date: 2021-05-11 15:26:13
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 17:01:22
 * @Auditor:
 */
import React, { useEffect } from 'react';
import Qs from 'query-string';
import PrintFormView from './../../components/printFormView/PrintFormView';
import style from './style.module.scss';
import { uploadIpfs } from './api';
import { printOnEveryPageClassName } from 'src/components/fd/printview/components/PrintRow';

// 转为blob文件
const dataURItoBlob = function (dataURI: any) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  let byteString;
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(dataURI.split(',')[1]);
  else
    byteString = unescape(dataURI.split(',')[1]);

  // separate out the mime component
  let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // write the bytes of the string to a typed array
  let ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], { type: mimeString });
};


const Print = () => {

  const query = Qs.parseUrl(window.location.href).query;

  const onLoad = () => {
    console.log('onload开始');

    if (query.pdf) {

      setTimeout(() => {
        console.log('创建开始');
        const $ = (window as any).$;

        let targetDom = $("#arrayPrint");
        if (targetDom.length === 0) {
          targetDom = $("#printStyle");
        }
        console.log(targetDom);

        let opt = {
          margin: [5, 0, 0, 0],
          pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
          filename: query.businessName || `测试文件`,
          image: {
            type: 'jpeg', quality: 0.95
          }
        };

        let pdf = (window as any).html2pdf()
          .from(targetDom[0])
          .set(opt)
          .toPdf();
        console.log('生成pdf');

        pdf.outputPdf("datauristring").then(async (base64: any) => {
          console.log('生成完成');

          let blob = dataURItoBlob(base64);
          let file = new File([blob], opt.filename + '.pdf', {
            type: "application/pdf"
          });
          console.log('file生成完成');
          let formData = new FormData();

          formData.append("file", file);
          console.log('file上传');
          // const res = await uploadIpfs(formData);
          // console.log(res, 'res');
          console.log('file上传完成');

          // 自动下载
          if (query.autoDownload) {
            const res = await uploadIpfs(formData);
            if (res.filename) {
              const parseFileName = Qs.parseUrl(res.filename);

              if (query.downloadFileName) {
                parseFileName.query.downloadFileName = query.downloadFileName;
              }

              window.location.href = `/bk/getFile/${parseFileName.url}?${Qs.stringify(parseFileName.query)}`;
            }
          }

          (window.parent as any).statusCheck = () => {
            return true;
          };

          (window.parent as any).uploadPdf = async () => {
            const res = await uploadIpfs(formData);

            console.log(res);
            return res;
          };

        });

      }, 1000);

    }
  };

  useEffect(() => {
    function handleBeforeprint() {
      if (document.querySelector(`.${style.printOnEveryPage}`)) {
        return;
      }

      const content = document.querySelector(`.${printOnEveryPageClassName}`);
      if (content) {
        const contentCopy = content.cloneNode(true);
        content?.classList.add(style.printHide);

        // 原本的表头
        const tablehead = document.querySelector('thead');
        const tr = tablehead?.firstChild;
        if (tr) {
          const rowsCount = tr.childNodes.length || 0;

          // 添加一行用于放置每页显示的内容
          const tr1 = document.createElement('tr');
          tr1.classList.add(style.printOnEveryPage);
          const th1 = document.createElement('th');
          th1.colSpan = rowsCount;
          th1.appendChild(contentCopy);
          tr1.appendChild(th1);

          // 表格标题
          const tableContainer = document.querySelector('.printview-table');
          const tableTitle = tableContainer?.children[0];
          if (tableTitle) {
            const tableTitleCopy = tableTitle.cloneNode(true);
            tableTitle?.classList.add(style.printHide);

            // 添加一行显示表格标题
            const tr2 = document.createElement('tr');
            tr2.classList.add(style.printOnEveryPage);
            const th2 = document.createElement('th');
            th2.colSpan = rowsCount;
            th2.appendChild(tableTitleCopy);
            tr2.appendChild(th2);
            tr.before(tr2);

            tr2.before(tr1);
          } else {
            tr.before(tr1);
          }

          // 添加一个表头，用于每页显示
          // const addtHead = document.createElement('thead');
          // addtHead.style.display = 'table-header-group';
          // addtHead.classList.add(style.printOnEveryPage);

          // 添加一行用于放置每页显示的内容
          // const tr1 = document.createElement('tr');
          // const th1 = document.createElement('th');
          // th1.colSpan = rowsCount;
          // th1.appendChild(contentCopy);
          // tr1.appendChild(th1);
          // if(tableTitle) {
          //   tr2.before(tr1)
          // }
          // addtHead.appendChild(tr1);

          // tablehead.before(addtHead);
        }
      }
    }

    window.onbeforeprint = handleBeforeprint;

    return () => {
      window.onbeforeprint = null;
    };
  });

  return (
    <div className={style.printContent}>
      <button className={style.printBtn} onClick={() => {
        window.print();
      }}>{window.$app.t('printing')}</button>
      <PrintFormView onLoad={onLoad} formId={query.formId as string} formName={decodeURIComponent(query.formName as string)} formDataId={query.formDataId as string} sessionkey={query.sessionkey as string} />
    </div>
  );
};

export default Print;
